package com.kyzh.core.pager.gamedetail

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Pinglun
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.requests.AppRequest
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.constant.Type
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.kyzh.core.R
import com.kyzh.core.dialog.hideKeyboard
import com.kyzh.core.utils.GlideEngine
import com.kyzh.core.utils.setVisibility
import com.kyzh.core.utils.startLogin
import com.gushenge.core.toast
import kotlinx.android.synthetic.main.activity_game_comment.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class GameCommentActivity : BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Activity, id:String, pid:String? , ppid:String? ,type:Int,pinglun : Pinglun? ) {
            val starter = Intent(context, GameCommentActivity::class.java)
                .putExtra("id",id).putExtra("pid",pid).putExtra("ppid",ppid).putExtra("type",type).putExtra("pinglun",pinglun)
            context.startActivityForResult(starter,100001)
        }

    }
    private  var id : String? = null
    private  var pid : String?= null
    private  var ppid : String?= null
    //传0   发表完关闭页面  传1调该评论详情
    private  var type : Int?= 0
    private var photos :ArrayList<Photo> = arrayListOf()
    private  var adapter : ImgAdapter =ImgAdapter(photos)
    private  var urlSubmit : ArrayList<String> = arrayListOf()
    private var typeVideo :Boolean = false
    private var pinglun: Pinglun?=null
    private var progressDialog :ProgressDialog?= null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game_comment)

        id = intent.getStringExtra("id")
        pid = intent.getStringExtra("pid")
        ppid = intent.getStringExtra("ppid")
        type = intent.getIntExtra("type",0)
        pinglun = intent.getSerializableExtra("pinglun") as Pinglun?
        initView()
        initData()
    }
    var pingLunContext: String = ""
    fun initView(){
        progressDialog = ProgressDialog(this)
        if(pid.isNullOrEmpty()){
            group.setVisibility(true)
        }else{
            group.setVisibility(false)
        }
        close.setOnClickListener {
            finish()
        }
        rvImages.adapter =adapter
        rvImages.layoutManager =object: GridLayoutManager(this@GameCommentActivity,3){
            override fun getSpanCount(): Int {
                return super.getSpanCount()
            }
        }
        ivAddImage.setOnClickListener {
            EasyPhotos.createAlbum(this@GameCommentActivity,false,false, GlideEngine)
                .complexSelector(true,1,9)
                .setSelectedPhotos(photos)
                .setVideo(true)
                .setGif(false)
                .start(object : SelectCallback() {
                    override fun onResult(photo: ArrayList<Photo>, isOriginal: Boolean) {
                        photos.clear()
                        photos.addAll(photo)
                        adapter.notifyDataSetChanged()
                    }

                    override fun onCancel() {

                    }
                })
        }
        tvSubmit.setOnClickListener {
            hideKeyboard(etContent)
            if(startLogin()){
            var urls :ArrayList<Uri> = arrayListOf()
            photos.forEach {
                typeVideo = it.type.contains(Type.VIDEO)
                urls.add(it.uri)
            }
             pingLunContext = etContent.text.trim().toString()
            if(pingLunContext.isNullOrEmpty()){
                Toast.makeText(this@GameCommentActivity,"请输入游戏评价", Toast.LENGTH_LONG).show()
                "请输入游戏评价".toast()
            }else {

                if(!urls.isNullOrEmpty()){
//                    Toast.makeText(this@GameCommentActivity,"上传中，请稍后..",Toast.LENGTH_LONG).show()
                    progressDialog?.setCancelable(false)
                    progressDialog?.setMessage("上传中，请稍后..")
                    progressDialog?.show()


                }
                if(urls.size==0){
                    val obtain = Message.obtain()
                    obtain.what = 1
                    handler.sendMessage(obtain)
                }else {

                    urlSubmit.clear()
                    GlobalScope.launch {
                        repeat(urls.size) {
                            AppRequest.uploadImageOrVideo(this@GameCommentActivity, urls[it]) {
                                progressDialog?.setMessage("上传进度${urlSubmit.size}/${urls.size}，请等待")
                                Log.e("TAG", "initView: $this", )
                                urlSubmit.add(this)
                                if (urlSubmit.size == urls.size) {

                                    val obtain = Message.obtain()
                                    obtain.what = 1
                                    handler.sendMessage(obtain)
                                }
                            }
                        }
                    }
                }
            }
            }
        }

    }



    private val handler = @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what ){
                1 ->{

                    if(typeVideo){
                        GameImpl.pushPingLun(this@GameCommentActivity,id!!,null,urlSubmit[0],pingLunContext,rbStar.rating.toString(),pid,ppid,type,
                            pinglun){
                            progressDialog?.dismiss()
                        }
                    }else{
                        GameImpl.pushPingLun(this@GameCommentActivity,id!!,urlSubmit,null,pingLunContext,rbStar.rating.toString(),pid,ppid,type,
                            pinglun){
                            progressDialog?.dismiss()
                        }
                    }
                }
            }
        }
    }
    fun initData(){
    }



    inner class ImgAdapter(var a:ArrayList<Photo>) :BaseQuickAdapter<Photo, BaseViewHolder>(R.layout.item_image,a){
        override fun convert(holder: BaseViewHolder, item: Photo) {
            val img1 = holder.getView<ImageView>(R.id.img)
            val delete = holder.getView<TextView>(R.id.delete)
            delete.setOnClickListener {
                photos.remove(item)
                notifyDataSetChanged()
            }
                Glide.with(context).load(item.uri.toString()).into(img1)

        }

    }
}
